<?php
namespace Andorra\drivers;

use Andorra\dao\Entity;
use Andorra\dao\EntityType;

class SqliteDriver extends DataDriver {
	private $conn;
	
	public function __construct(\DOMElement $node) {
		$this->conn = new \SQLite3(trim($node->textContent));
	}
	
	public function __destruct() {
		$this->conn->close();
	}
	
	public function getEntities(EntityType $e) {
		$sql = 'SELECT * FROM "' . $e->name . '"';
		$result = $this->conn->query($sql);
		
		return $this->resultToArray($result);
	}
	
	public function getEntityById(EntityType $e, $id) {
		$sql = 'SELECT *
				FROM "' . $e->name . '"
				WHERE "' . $e->key . '" = ' . $id;
		$result = $this->conn->query($sql);
		
		return $result->fetchArray(SQLITE3_ASSOC);
	}
	
	public function getMaxId(EntityType $e) {
		$sql = 'SELECT MAX("' . $e->key . '")
				FROM "' . $e->name . '"';
		$result = $this->conn->query($sql);
		
		return $this->resultToArray($result);
	}
	
	public function putEntity(Entity $e) {
		$key = $e->entityType->key;
		
		$sql = 'INSERT INTO "' . $e->entityType->name . '"';
		$sql .= '("' . $key . '", "';
		$sql .= implode('", "', $e->entityType->columns) . '")';
		$sql .= " VALUES('" . $e->$key . "', ";
		
		foreach ($e->entityType->columns as $column)
			$sql .= "'" . $e->$column . "',";
		
		$sql = rtrim($sql, ',');
		$sql .= ')';
		
		$this->conn->query($sql);
	}
	
	private function resultToArray(\SQLite3Result $result) {
		$rows = array();
		while ($rows[] = $result->fetchArray(SQLITE3_ASSOC)) ;
		
		array_pop($rows);
		return $rows;
	}
}